<?php
namespace app\admin\controller;
use app\admin\validate\MarketValidate;
use app\service\MarketService;
use think\exception\ValidateException;

class Market extends Admin
{

    public function __construct(MarketService $service)
    {
        parent::__construct();
        $this->service = $service;
    }

    public function index()
    {
        if (!$this->request->isPost()) {
            $this->assign("title","币种类别，参考火币，K线图主要从火币获取");
            return $this->fetch("index");
        }
        $params = $this->request->post();
        $where =[];
        if (!empty($params["code"])) {
            $where[] = ['code', 'like', "%{$params['code']}%"];
        }
        if (!empty($params["status"])) {
            $where[] =["status" ,"=",$params["status"]];
        }
        $ret = $this->service->getList($where);
        $this->result($ret);
    }

    private function save()
    {
        $params = $this->request->Post();
        $data =[
            "code"=>$params["code"],
            "icon"=>$params["icon"],
            "id"=>$params["id"] ?? 0,
            "sort"=>$params["sort"],
            "is_primary"=>$params["is_primary"]
        ];
        $action = $this->request->action();
        try {
            validate(MarketValidate::class)->scene($action)->check($data);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $ret = $this->service->save($data);
        if ($ret) {
            $this->success("操作成功");
        } else {
            $this->error("保存失败");
        }
    }
    public function add()
    {
        if (!$this->request->isPost()) {
            $this->assign("vo",["is_primary"=>1]);
            return $this->fetch("form");
        }
        $this->save();
    }

    public function edit()
    {
        if (!$this->request->isPost()) {
            $id = $this->request->get("id");
            if (!$id) {
                throw new ValidateException("缺少id");
            }
            $vo = $this->service->get($id);
            if (empty($vo)) {
                throw new ValidateException("分类不存在");
            }
            $this->assign("vo",$vo);
            return $this->fetch("form");
        }
        $this->save();
    }


    public function setStatus()
    {
        $params = $this->request->Post();
        try {
            validate(MarketValidate::class)->scene("status")->check($params);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $this->service->setStatus($params["id"],$params["status"]);
        $this->success("操作成功");
    }
}